﻿using psafth.RCTiming.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace psafth.RCTiming.Main
{
    public class EventHelper
    {
        public static List<Heat> CreateRacingHeats(Event ev)
        {

            foreach (IEnumerable<EventParticipant> group in ev.Participants.GroupBy(r => r.RaceClassId))
            {
                List<Heat> groupHeats = new List<Heat>();

                List<EventParticipant> groupParticipants = group.ToList();

                int minNumbOfCompetitors = 4;

                int numberOfCompetitors = groupParticipants.Count();

                if (numberOfCompetitors < minNumbOfCompetitors)
                    continue;

                int leftOvers;

                int maxNumbPerheat = 12;
                int numberOfGroups = Math.DivRem(numberOfCompetitors, maxNumbPerheat, out leftOvers);

                if (leftOvers > 0)
                    numberOfGroups++;

                int numberPerGroup = Math.DivRem(numberOfCompetitors, numberOfGroups, out leftOvers);

                //int leftOvers = numberOfCompetitors % numberOfGroups;

                int partIndex = 0;

                for (int i = 1; i <= numberOfGroups; i++)
                {
                    Heat h = new Heat();

                    h.Name = string.Format("{0} - {1} - {2}", ev.EventName, string.Empty, string.Empty);

                    for (int n = 1; n <= numberPerGroup; n++)
                    {
                        EventParticipant p = groupParticipants[partIndex];

                        h.HeatCompetitors.Add(new HeatCompetitor(p.Driver, p.TransponderId));
                        partIndex++;
                    }

                    //if (g < maxNumbPerheat && leftOvers > 0)
                    //{
                    //    g++;
                    //    leftOvers--;
                    //}

                    //groups.Add(g);
                }
            }


            return new List<Heat>();
        }
    }
}
